#include "FaceDetector.h"  
#include <iostream>  

FaceDetector::FaceDetector(const std::string& face_cascade_path, const std::string& eyes_cascade_path, const std::string& smile_cascade_path) {  
    if (!face_cascade.load(face_cascade_path)) {  
        std::cerr << "Error loading cascade file: " << face_cascade_path << std::endl;  
        exit(EXIT_FAILURE);  
    }  

    if (!eyes_cascade.load(eyes_cascade_path)) {  
        std::cerr << "Error loading eyes cascade file: " << eyes_cascade_path << std::endl;  
        exit(EXIT_FAILURE);  
    }  

    if (!smile_cascade.load(smile_cascade_path)) {  
        std::cerr << "Error loading smile cascade file: " << smile_cascade_path << std::endl;  
        exit(EXIT_FAILURE);  
    }  
}  

void FaceDetector::detectAndDisplay(cv::Mat& frame) {  
    std::vector<cv::Rect> faces;  
    cv::Mat gray;  
    cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);  
    cv::equalizeHist(gray, gray);  

    // 检测人脸  
    face_cascade.detectMultiScale(gray, faces, 1.2, 4, 0, cv::Size(30, 30));  

    for (size_t i = 0; i < faces.size(); i++) {  
        cv::rectangle(frame, faces[i], cv::Scalar(255, 0, 0), 2);  
        std::string face_info = "Face " + std::to_string(i + 1);  
        cv::putText(frame, face_info, faces[i].tl(), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 1);  

        cv::Mat faceROI = gray(faces[i]);  
        std::vector<cv::Rect> eyes;  
        eyes_cascade.detectMultiScale(faceROI, eyes, 1.20, 4, 0, cv::Size(30, 30));  

        // 检测眼睛  
        for (size_t j = 0; j < eyes.size(); j++) {  
            cv::Rect eye_rect(faces[i].x + eyes[j].x, faces[i].y + eyes[j].y, eyes[j].width, eyes[j].height);  
            cv::rectangle(frame, eye_rect, cv::Scalar(0, 255, 0), 2);  
        }  

        // 检测微笑  
        std::vector<cv::Rect> smiles;  
        smile_cascade.detectMultiScale(faceROI, smiles, 1.8, 10, 0, cv::Size(25, 25));  

        for (size_t k = 0; k < smiles.size(); k++) {  
            cv::Rect smile_rect(faces[i].x + smiles[k].x, faces[i].y + smiles[k].y + faces[i].height / 2, smiles[k].width, smiles[k].height / 2);  
            cv::rectangle(frame, smile_rect, cv::Scalar(0, 255, 255), 2);  
            cv::putText(frame, "Smile", cv::Point(smile_rect.x, smile_rect.y - 10), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255), 1);  
        }  
    }  
}